<template>
  <div class="base-freight-table">
    <div class="table-container">
      <div class="main-table-wrapper">
        <table class="main-table">
          <thead>
          <tr>
            <th v-for="header in visibleHeaders" :key="header.field" :class="{ 'resizable': true }">
              {{ header.text }}
              <div class="resize-handle"></div>
            </th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(row, i) in visibleTableData"
              :key="row.id"
              :class="{ 'selected-row': i === selectedMainRowIndex }"
              @click="handleRowFocus(row, i)">
            <td v-for="header in visibleHeaders" :key="header.field">
              <component
                  :is="getCellComponent(header.cellType)"
                  v-model="row[header.field]"
                  :column-width="header.width"
                  :search-obj="header.searchObj"
                  :comboxlist="header.comboxlist"
                  @update:model-value="(value) => handleCellUpdate(i, header.field, value)"
                  @focus="() => handleRowFocus(row, i)"
                  @input="(event) => handleCellInput(i, header.field, event)"
                  v-if="shouldRenderComponent(header, row)"
              />
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <div class="matching-locations">
        <h3>Matching Locations</h3>
        <table>
          <thead>
          <tr>
            <th v-for="header in matchingLocationsHeaders" :key="header">{{ header }}</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(row, index) in matchingLocationsData" :key="index">
            <td v-for="header in matchingLocationsHeaders" :key="header">{{ row[header.toLowerCase()] }}</td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="fee-table-wrapper">
      <table class="fee-table">
      <thead>
      <tr>
        <th v-for="header in feeHeaders" :key="header.field">{{ header.text }}</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(row, index) in filteredFeeData" :key="row.id">
        <td v-for="header in feeHeaders" :key="header.field">
          <component
              :is="getCellComponent(header.cellType)"
              v-model="row[header.field]"
              :column-width="header.width"
              :search-obj="header.searchObj"
              @update:model-value="(value) => handleFeeCellUpdate(index, header.field, value)"
          />
        </td>
      </tr>
      </tbody>
    </table>
    </div>
    <CalculatorSection
        :calculators="calculators"
        @calculator-selected="onCalculatorSelected"
        @unit-price-change="onUnitPriceChange"
        @agent-rate-change="onAgentRateChange"
    />
  </div>
</template>

<script>
import { computed, onMounted, watch } from 'vue'
import CalculatorSection from './CellComponents/Calculator/CalculatorSection.vue'
import { useTableData } from './useTableData'
import { getCellComponent } from './cellComponents'

export default {
  name: 'BaseFreightTable',
  components: {
    CalculatorSection
  },
  props: {
    businessType: {
      type: String,
      default: ''
    },
    tableData: {
      type: [Array, Object],
      default: () => []
    },
    calculators: {
      type: Array,
      default: () => []
    },
    headers: {
      type: Array,
      required: true
    },
    matchingLocationsHeaders: {
      type: Array,
      default: () => ['Field', 'Location']
    },
    matchingLocationsData: {
      type: Array,
      required: true
    },
    feeHeaders: {
      type: Array,
      required: true
    },
    feeData: {
      type: Array,
      required: true
    }
  },
  emits: [
    'update:tableData',
    'update:feeData',
    'calculatorSelected',
    'unitPriceChange',
    'agentRateChange',
    'rowFocus'
  ],
  setup(props, { emit }) {
    const visibleHeaders = computed(() => props.headers.filter(header => header.visible !== false))

    const shouldRenderComponent = (header) => {
      if (header.cellType === 'cellCombobox') {
        return header.comboxlist && header.comboxlist.data && header.comboxlist.data.length > 0;
      }
      return true;
    };

    const {
      localTableData,
      localFeeData,
      selectedMainRowIndex,
      filteredFeeData,
      handleCellUpdate,
      handleCellInput,
      handleRowFocus,
      handleFeeCellUpdate,
      onCalculatorSelected,
      onUnitPriceChange,
      onAgentRateChange,
      visibleTableData,

    } = useTableData(props, emit)

    onMounted(() => {
      // Any necessary initialization
    });

    watch(() => props.tableData, () => {
      // Handle table data changes if necessary
    }, { deep: true });

    return {
      visibleHeaders,
      shouldRenderComponent,
      getCellComponent,
      localTableData,
      localFeeData,
      selectedMainRowIndex,
      filteredFeeData,
      handleCellUpdate,
      handleCellInput,
      handleRowFocus,
      handleFeeCellUpdate,
      onCalculatorSelected,
      onUnitPriceChange,
      onAgentRateChange,
      visibleTableData
    }
  }
}
</script>

<style scoped>
.base-freight-table {
  font-family: Arial, sans-serif;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.table-container {
  display: flex;
  margin-bottom: 20px;
  height: 25vh;
  min-height: 200px;
}

.main-table-wrapper {
  flex: 1;
  overflow-x: auto;
  overflow-y: auto;
  height: 100%;
}

.main-table {
  width: 100%;
  border-collapse: collapse;
}

.fee-table-wrapper {
  margin-top: 20px;
  overflow-x: auto; /* 允许水平滚动 */
  width: 100%; /* 确保wrapper占满容器宽度 */
}

.fee-table {
  min-width: 100%; /* 确保表格至少和容器一样宽 */
  border-collapse: collapse;
}

.main-table th, .main-table td,
.fee-table th, .fee-table td,
.matching-locations th, .matching-locations td {
  border: 1px solid #ddd;
  padding: 8px;
  font-size: 14px;
  white-space: nowrap; /* 防止文本换行 */
}

.main-table th, .fee-table th, .matching-locations th {
  background-color: #f2f2f2;
  font-weight: bold;
  position: sticky;
  top: 0;
  z-index: 10;
}

.fee-table th {
  position: sticky;
  left: 0;
  z-index: 20; /* 确保表头在滚动时始终可见 */
}

.resizable {
  position: relative;
}

.resize-handle {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 5px;
  cursor: col-resize;
}

.matching-locations {
  width: 300px;
  margin-left: 20px;
  overflow-y: auto;
  height: 100%;
}

.matching-locations table {
  width: 100%;
}

.selected-row {
  background-color: #e6f7ff;
}

@media (max-width: 1024px) {
  .table-container {
    flex-direction: column;
    height: auto;
  }

  .main-table-wrapper, .matching-locations {
    height: 33vh;
  }

  .matching-locations {
    width: 100%;
    margin-left: 0;
    margin-top: 20px;
  }
}
</style>
